﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Web;

namespace DBA.Data.Hibernate
{
    public sealed class SessionManager
    {
        private static readonly ISessionFactory _sessionFactory;
        private const string CurrentSessionKey = "nhibernate.current_session";

        static SessionManager()
        {
            _sessionFactory = new Configuration().Configure().BuildSessionFactory();

        }

        private SessionManager()
        {
        }     

        /// <summary>
        /// 取得当前Session
        /// </summary>
        /// <returns></returns>
        public static ISession GetSession()
        {
            //?return _sessionFactory.OpenSession();
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                currentSession = _sessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
            }
            return currentSession;
        }

        public static  ISessionFactory GetSessionFactory()
        {
            return new Configuration().Configure().BuildSessionFactory();
        }

        /// <summary>
        /// 关闭当前Session
        /// </summary>
        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                // No current session
                return;
            }
            currentSession.Close();
            context.Items.Remove(CurrentSessionKey);
        }

        /// <summary>
        /// 关闭Factory
        /// </summary>
        public static void CloseSessionFactory()
        {
            if (_sessionFactory != null)
            {
                _sessionFactory.Close();
            }
        }
    }
}
